package com.example.demo.controller;


import com.example.demo.entity.Employee;
import com.example.demo.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Value("${spring.servlet.multipart.location}") // 注入配置路径
    private String uploadDir;

    @Autowired
    private EmployeeMapper employeeMapper;

    @ResponseBody
    @RequestMapping(value = "/getName", method = RequestMethod.GET)
    public Object getName(){
        return "张三";
    }


    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public Object selectAll(){
        return employeeMapper.selectAll();
    }

    @ResponseBody
    @PostMapping("/register")
    public  Employee register(@RequestBody Employee employee){
        System.out.println(employee);
        employeeMapper.register(employee);
        return employee;
    }

    @PostMapping("/uploadAvatar")
    public ResponseEntity<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        // 检查文件类型
        if (!file.getContentType().startsWith("image/")) {
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "请上传图片文件"));
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + fileExtension;

        // 保存到avatars目录
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();

        try {
            File destFile = new File(uploadDir + newFilename);
            file.transferTo(destFile);
            String filePath = destFile.getName();
            return ResponseEntity.ok(Collections.singletonMap("url", "/avatar/"+filePath));
        } catch (IOException e) {
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "上传失败: " + e.getMessage()));
        }
    }
}
